package com.ym.ganio.net;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ym.ganio.bean.ArticleItem;
import com.ym.ganio.define.ReadDefine;
import com.yumo.common.net.YmOkHttpUtil;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Response;

/**
 * Created by yumodev on 17/6/4.
 */

public class GanApiNetHelper {
    private static final String LOG_TAG = "GanApiHelper";
    /**
     * http://gank.io/api/data/Android/10/1
     * 获取分类的第几页
     * @param type
     * @param num
     * @param page
     */
    public static GanApiResult getTypeDataByPage(String type, int num, int page){
        String url = String.format(Locale.getDefault(), "http://gank.io/api/data/%s/%d/%d", type, num, page);
        Log.i(LOG_TAG, "getTypeDataByPage url:"+url);
        try {
            Response response = YmOkHttpUtil.getBodyResponse(url);
            if (response != null && response.isSuccessful()){
                String result = response.body().string();
                Log.i(LOG_TAG, "getTypeDataByPage:"+result);
                return paresDataResult(result);
            }
        }catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }

    private static GanApiResult paresDataResult(String jsonStr){
        if (jsonStr == null) return null;

        GanApiResult result = new GanApiResult();

        try {
            JSONObject json = JSON.parseObject(jsonStr);

            if (json.containsKey(ReadDefine.JSON_KEY_ERROR)){
                result.setError(json.getBoolean(ReadDefine.JSON_KEY_ERROR));
            }

            if (json.containsKey(ReadDefine.JSON_KEY_RESULTS)){
                List<ArticleItem> dataList = new ArrayList<>();
                JSONArray jsonArray = json.getJSONArray(ReadDefine.JSON_KEY_RESULTS);
                for (int i = 0; i < jsonArray.size(); i++){
                    dataList.add(convertJsonToReadItem(jsonArray.getJSONObject(i)));
                }
                result.setResults(dataList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return result;
    }

    private static ArticleItem convertJsonToReadItem(JSONObject json){
        ArticleItem data = JSONObject.toJavaObject(json, ArticleItem.class);
        return data;
    }
}
